package addon

import (
	"context"
	"errors"
	"nexus/internal/config"

	"github.com/zeromicro/go-zero/core/stores/redis"
)

type RedisAddons struct {
	rds *redis.Redis
}

func NewRedis(c config.Config) *RedisAddons {
	conf := redis.RedisConf{
		Host: c.Redis.Host,
		Type: c.Redis.Type,
		Pass: c.Redis.Pass,
		Tls:  false,
	}

	rds := redis.MustNewRedis(conf)
	if rds == nil {
		panic("redis init failed")
	}
	return &RedisAddons{rds: rds}
}

// SetnxEx 原子插入指定数据
func (r *RedisAddons) SetnxEx(ctx context.Context, key, value string, second int) error {
	ok, err := r.rds.SetnxExCtx(ctx, key, value, second)
	if err != nil {
		return err
	}
	if !ok {
		return errors.New("setnxex fail")
	}
	return err
}

// GetKey 获取指定数据
func (r *RedisAddons) GetKey(ctx context.Context, key string) (string, error) {
	return r.rds.Get(key)
}

// SetKey 插入指定数据
func (r *RedisAddons) SetKey(ctx context.Context, key, value string, second int) error {
	if err := r.rds.Setex(key, value, second); err != nil {
		return err
	}
	return nil
}

// Del 删除指定数据
func (r *RedisAddons) Del(ctx context.Context, key ...string) error {
	_, err := r.rds.Del(key...)
	if err != nil {
		return err
	}
	return err
}

// Keys 获取所有key
func (r *RedisAddons) Keys(ctx context.Context, pattern string) (result []string, err error) {
	return r.rds.KeysCtx(ctx, pattern)
}

// 判断key是否存在
func (r *RedisAddons) Exists(ctx context.Context, key string) (bool, error) {
	return r.rds.ExistsCtx(ctx, key)
}
